package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.common.ReggieContext;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public R<List<ShoppingCart>> getShoppingCart(){

       return R.success(shoppingCartService.list(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, ReggieContext.get())
               .orderByDesc(ShoppingCart::getCreateTime)));

        //return  R.success(new ArrayList<>());
    }

    // 添加
    @PostMapping("/add")
    public R<ShoppingCart> addShoppingCart(@RequestBody ShoppingCart shoppingCart){
        ShoppingCart cart = shoppingCartService.add(shoppingCart);
        return R.success(cart);
    }

    // 清空购物车
    @DeleteMapping("/clean")
    public R<String> cleanShoppingCart(){
        // delete   from shopping_cart where user_id = ?
        shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId,ReggieContext.get()));
        return  R.success("清空成功");
    }

    // 数量-1  为0时删除
    @PostMapping("/sub")
    public R<String> subShoppingCart(@RequestBody ShoppingCart shoppingCart){
       shoppingCartService.sub(shoppingCart);
        return R.success("删减成功");
    }
}
